# _*_ coding: utf-8 _*_
# @Time:2024/5/17 10:37
# @Author:10917
# @File:custom_paginations.py
from django.core.paginator import InvalidPage
from rest_framework.exceptions import NotFound
from rest_framework.pagination import PageNumberPagination
from rest_framework.response import Response


class CustomPageNumberPagination(PageNumberPagination):
    """
    自定义分页器，需要继承  PageNumberPagination
    """
    page_size = 3  # 每页多少条数据
    page_size_query_param = 'size'  # 设置了每页size的参数名
    max_page_size = 3  # 设置每页最大数据条数

    def paginate_queryset(self, queryset, request, view=None):
        """
        重写方法，当页码超过最大页码数时，默认返回第1页的数据
        :param queryset:
        :param request:
        :param view:
        :return:
        """
        self.request = request
        page_size = self.get_page_size(request)
        if not page_size:
            return None

        self.page_size = page_size

        paginator = self.django_paginator_class(queryset, page_size)
        page_number = request.query_params.get(self.page_query_param, 1)

        try:
            self.page = paginator.page(page_number)
            return list(self.page)
        except InvalidPage as exc:
            if int(page_number) > paginator.num_pages:
                self.page = paginator.page(1)  # 返回第1页的数据
                return list(self.page)
            else:
                raise NotFound('Page not found')

    def get_paginated_response(self, data):
        """
        自定义分页器的响应结构
        :param data:
        :return:
        """
        return Response({
            'status': '1',
            'data': {
                'list': data,
                'paginations': {
                    'current_page': self.page.number,
                    'last_page': self.page.paginator.num_pages,
                    'per_page': self.page_size,
                    'total': self.page.paginator.count,
                }
            }
        })
